<?php
/**
 * Created by INGEPHP CURD.
 * User:
 * Date: 2018/10/16
 * Time: 10:16
 */

namespace app\admin\service;


use app\admin\model\PlatformWechatModel;

class PlatformWechatService
{
    /**
     * 获取列表
     * @param int $page 分页
     * @param int $limit 每页数量
     * @param string $keyword 搜索关键词
     * @return json
     */
    public function getList($page = 1, $limit = 15, $keyword = "")
    {
        if (!empty($keyword)) {
            $map[] = ['name', 'like', '%' . $keyword . '%'];
            $list = PlatformWechatModel::where($map);
        } else {
            $list = new PlatformWechatModel;
        }
        $total = clone $list;
        $list = $list->page($page, $limit)->select();
        $total = $total->count();
        return ['code' => 1001, 'msg' => '获取成功', 'data' => $list, 'total' => $total];
    }

    /**
     * 新增数据
     * @param array 传入的数据
     * @return json
     */
    public function save($data)
    {
        $PlatformWechat = new PlatformWechatModel;
        $res = $PlatformWechat->save($data);
        if ($res) {
            return ['code' => 1001, 'msg' => '新增成功', 'data' => $res];
        }
        return ['code' => 4001, 'msg' => '新增失败', 'data' => ''];
    }

    /**
     * 根据ID更新数据
     * @param int $id 需要更新的数据ID
     * @param array 传入的数据
     * @return json
     */
    public function update($id, $data)
    {
        $PlatformWechat = new PlatformWechatModel;
        $res = $PlatformWechat->save($data, ['id' => $id]);
        if ($res) {
            return ['code' => 1001, 'msg' => '更新成功', 'data' => $res];
        }
        return ['code' => 4001, 'msg' => '更新失败', 'data' => ''];
    }

    /**
     * 根据ID删除数据
     * @param int $id 需要更新的数据ID
     * @return json
     */
    public function delete($id)
    {
        $res = PlatformWechatModel::destroy($id);
        if ($res) {
            return ['code' => 1001, 'msg' => '删除成功', 'data' => $res];
        }
        return ['code' => 4001, 'msg' => '删除失败', 'data' => ''];
    }

    /**
     * 根据ID获取数据
     * @param int $id
     * @return json
     */
    public function getById($id)
    {
        $PlatformWechat = new PlatformWechatModel;
        $res = $PlatformWechat::where('id', $id)->find();
        if ($res) {
            return ['code' => 1001, 'msg' => '获取成功', 'data' => $res];
        }
        return ['code' => 4001, 'msg' => '数据不存在', 'data' => ''];
    }

    /**
     * 根据ID切换数据status
     * User: Thans
     * Date: 2018/10/17
     * Time: 11:42
     * @param int $id
     * @return
     */
    public function toggle($id)
    {
        $PlatformWechat = new PlatformWechatModel;
        $res = $PlatformWechat::get($id);
        if(!$res){
            return ['code' => 4001, 'msg' => '数据不存在', 'data' => ''];
        }
        if($res['status']){
            $res->status = 0;
            $res->save();
        }else{
            $res->status = 1;
            $res->save();
        }
        return ['code' => 1001, 'msg' => '切换状态成功', 'data' => ''];
    }
}